package com.zhouyong.leetcode.合并两个有序链表21;

import com.zhouyong.leetcode.ListNode;

import java.util.Objects;

/**
 * @Author 99
 * @Date 2022/8/29 11:05
 * @Version 1.0
 */
public class Test {

    public static void main(String[] args) {

        //将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的
        //输入：l1 = 1->2->4, l2 = 1->3->4
        //输出：1->1->2->3->4->4
        ListNode node = new ListNode(1, new ListNode(2, new ListNode(4, null)));
        ListNode node1 = new ListNode(1, new ListNode(3, new ListNode(4, null)));
        System.out.println(mergeTwoLists(node, node1));
    }

    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode newNode = new ListNode(-2);
        ListNode middleNode = newNode;

        while (Objects.nonNull(l1) && Objects.nonNull(l2)) {
            if (l1.val < l2.val) {
                middleNode.next = l1;
                l1 = l1.next;
            } else {
                middleNode.next = l2;
                l2 = l2.next;
            }
            middleNode = middleNode.next;
        }
        //输入：l1 = [], l2 = [0]
        //输出：[0]
        middleNode.next = Objects.isNull(l2) ? l1 : l2;
        return newNode.next;
    }
}
